package com.cat2bug.junit.listener;

import com.cat2bug.junit.service.IReport;
import com.cat2bug.junit.service.FunctionTestClassReportService;
import com.cat2bug.junit.service.report.*;
import com.cat2bug.junit.service.report.html.CompileFailHtmlReportService;
import com.cat2bug.junit.service.report.html.HtmlReportService;
import com.cat2bug.junit.service.report.html.TestFailHtmlReportService;
import com.cat2bug.junit.util.AppUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.runner.Description;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
import org.junit.runner.notification.RunListener;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 测试结果监听
 */
public class Cat2BugRunListener extends Cat2BugAutoRunListener {
	private Logger log = LogManager.getLogger(Cat2BugRunListener.class);
	private final static List<IReport> reports = new ArrayList<>();

	private Class<?> testCaseClass;

	public Cat2BugRunListener(Class<?> testCaseClass) {
		this.testCaseClass = testCaseClass;

		reports.add(new CompileConsoleReportService());
		reports.add(new ConsoleReportService());
		reports.add(new TestFailHtmlReportService());
		reports.add(new CompileFailHtmlReportService());
		reports.add(new HttpInterfaceConsoleReport());

		AbstractTableReport[] tableReports = reports.stream().filter(r->r instanceof AbstractTableReport).collect(Collectors.toList()).toArray(new AbstractTableReport[0]);
		reports.add(new PushReportService(testCaseClass,tableReports));
		// 最后执行
		reports.add(new HtmlReportService(tableReports));
	}

	@Override
	public void testRunFinished(Result result) throws Exception {
		super.testRunFinished(result);

		// 打印商标
		String banner = AppUtils.getBanner();
		System.out.println(banner);
		// 执行报告
		this.reports.forEach(r->{
			try {
				Object report = r.getReport();
				if (report != null) {
					System.out.println("Title: " + r.getTitle());
					System.out.println(report);
				}
			}catch (Exception e){
				log.error(e);
			}
		});
	}
}
